#!/usr/bin/env python

import sys
try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk,gobject
    import gtk.glade
except:
    sys.exit(1)


import commonGUIElements,os,re#,custom_utils
gladeFile = "GeoEntityScanner.glade"

class GUI:
    
    def __init__(self):
        self.wTree = gtk.glade.XML(gladeFile, "MainWindow")

        dic = { "on_delete_event" : self.delete_event,
                "on_destroy" : gtk.main_quit,
                "on_Open" : self.Open_Clicked,
                "on_Save_As" : self.Save_As_Clicked,
                "on_New" : self.New_Clicked,
                "on_Save" : self.Save_Clicked,
                "on_Quit" : self.Quit_Clicked,
                "on_Cut" : self.Cut_Clicked,
                "on_Copy" : self.Copy_Clicked,
                "on_Paste" : self.Paste_Clicked,
                "on_About" : self.About_Clicked,
                "on_Action_One" : self.Action_One }
            
        self.wTree.signal_autoconnect(dic)

        self.unnamed_filecounter = 0
        self.fileName = "Untitled0"
        self.Extension = "xml"
        self.named = False        

        #Setup textview/textbuffer
        self.textBuffer = gtk.TextBuffer()
        self.textBuffer.set_text("")
        self.textView = self.wTree.get_widget("TextView")
        self.textView.set_buffer(self.textBuffer)
        #self.textView.set_wrap_mode(gtk.WRAP_WORD)
        self.textBuffer.set_modified(False)

        #Setup the status bar
        self.statusbar = self.wTree.get_widget("statusbar")
        self.statusbar_contextID = self.statusbar.get_context_id("mainwindow")
        self.statusbar_messageID = self.statusbar.push(self.statusbar_contextID,
                                                       self.fileName+"."+self.Extension)
        self.CornerLabel = self.wTree.get_widget("CLabel")

        #Setup the clipboard
        self.clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
        return
        
    def Copy_Clicked(self, widget):
        self.textBuffer.copy_clipboard(self.clipboard)
        return
        
    def Paste_Clicked(self, widget):
        self.textBuffer.paste_clipboard(self.clipboard, None, True)
        return

    def Cut_Clicked(self, widget):
        self.textBuffer.cut_clipboard(self.clipboard, True)
        return
        
    def About_Clicked(self, widget):
        self.aboutTree = gtk.glade.XML(gladeFile, "AboutDialog")
        self.about_dlg = self.aboutTree.get_widget("AboutDialog")
        self.about_dlg.run()
        self.about_dlg.destroy()
        return

    def New_Clicked(self, widget):
        """
        Check if current file is saved. If not, prompt for
        saving. After that close that file and open a new one.
        """

        if self.textBuffer.get_modified() == True:
            #Code to display a Yes/No dialog and get the result.
            name = self.fileName+"."+self.Extension
            result = commonGUIElements.yes_no_dlg("Save current file "+name+"?")
            if result == gtk.RESPONSE_YES:
                self.Save_Clicked(widget)

        print "New"
        self.unnamed_filecounter += 1
        self.fileName = "Untitled"+str(self.unnamed_filecounter)
        self.named = False
        self.textBuffer.set_text("")
        self.textBuffer.set_modified(False)
        
        #Setup the status bar
        self.statusbar.remove(self.statusbar_contextID, self.statusbar_messageID)
        self.statusbar_messageID = self.statusbar.push(self.statusbar_contextID,
                                                       self.fileName+"."+self.Extension)        
        return

    def Save_As_Clicked(self, widget):

        print "Save As activated"
        #Get a file name to save it under
        fileName = self.file_browse(gtk.FILE_CHOOSER_ACTION_SAVE, 
                                    "Select a location and filename to save:",
                                    self.fileName+"."+self.Extension)

        if fileName == "":
            return

        tList = fileName.rsplit(".", 1)
        self.fileName = tList[0]
        if len(tList) == 1:
            self.Extension = ""
        else:
            self.Extension = tList[1]
        self.named = True

        #Setup the status bar
        self.statusbar.remove(self.statusbar_contextID, self.statusbar_messageID)
        self.statusbar_messageID = self.statusbar.push(self.statusbar_contextID,
                                                       self.fileName+"."+self.Extension)        


        #got file name. do the actual file saving.
        self.Save_Clicked(widget)
        return

    def Save_Clicked(self, widget):
        #Check if file has a name
        if self.named == False:
            self.Save_As_Clicked(widget)
            return
        
        if self.textBuffer.get_modified() == False:
            return

        #Save it
        print "Saving file..."
        f = open(self.fileName+"."+self.Extension, "w")
        start = self.textBuffer.get_start_iter()
        end = self.textBuffer.get_end_iter()
        f.write(self.textBuffer.get_text(start, end))
        self.textBuffer.set_modified(False)
        return

    def Open_Clicked(self, widget):
        print "Open Clicked"        

        #Check if current file has unsaved info.
        if self.textBuffer.get_modified():
            fname = self.fileName+"."+self.Extension
            response = commonGUIElements.yes_no_dlg("Save file \""+fname+"\"?")
            if response == gtk.RESPONSE_YES:
                self.Save_Clicked(widget)
                
        #Get a filename
        fileName = self.file_browse(gtk.FILE_CHOOSER_ACTION_OPEN, "Select a file to open:")

        #If no file name was got, nothing to do.
        if fileName == "":
            return

        #Store the name so that it can be accessed by other methods
        tList = fileName.rsplit(".", 1)
        self.fileName = tList[0]
        if len(tList) == 1:
            self.Extension = ""
        else:
            self.Extension = tList[1]
        self.named = True

        #Open the file and display it to the user.
        print "You selected: ", fileName
        f = open(fileName, "r")
        self.textBuffer.set_text(f.read())
        f.close()
        self.textBuffer.set_modified(False)

        #Setup the status bar
        self.statusbar.remove(self.statusbar_contextID, self.statusbar_messageID)
        self.statusbar_messageID = self.statusbar.push(self.statusbar_contextID,
                                                       self.fileName+"."+self.Extension)
        return

    def Quit_Clicked(self, widget):
        print "quit clicked"
        
        #Check if current file has unsaved info.
        if self.textBuffer.get_modified():
            fname = self.fileName+"."+self.Extension
            response = commonGUIElements.yes_no_dlg("Save file \""+fname+"\"?")
            if response == gtk.RESPONSE_YES:
                self.Save_Clicked(widget)

        gtk.main_quit()

    def delete_event(self, widget, event):
        print "delete event happened"
        
        #Check if current file has unsaved info.
        if self.textBuffer.get_modified():
            fname = self.fileName+"."+self.Extension
            response = commonGUIElements.yes_no_dlg("Save file \""+fname+"\"?")
            if response == gtk.RESPONSE_YES:
                self.Save_Clicked(widget)

        return False
        
    def file_browse(self, dialog_action, title, file_name=""):
        """This function is used to browse for a text file.  It can be either
        a save or open dialog depending on what dialog_action is.  The
        path to the file will be returned if the user selects one,
        however a blank string will be returned if they cancel or do
        not select one.  dialog_action - The open or save mode for the
        dialog either gtk.FILE_CHOOSER_ACTION_OPEN,
        gtk.FILE_CHOOSER_ACTION_SAVE file_name - Default name when
        doing a save"""

	if (dialog_action==gtk.FILE_CHOOSER_ACTION_OPEN):
            dialog_buttons = (gtk.STOCK_CANCEL
                              , gtk.RESPONSE_CANCEL
                              , gtk.STOCK_OPEN
                              , gtk.RESPONSE_OK)
	else:
            dialog_buttons = (gtk.STOCK_CANCEL
                              , gtk.RESPONSE_CANCEL
                              , gtk.STOCK_SAVE
                              , gtk.RESPONSE_OK)
            
        file_dialog = gtk.FileChooserDialog(title=title
                                            , action=dialog_action
                                            , buttons=dialog_buttons)

        """set the filename if we are saving"""
        if (dialog_action==gtk.FILE_CHOOSER_ACTION_SAVE):
            file_dialog.set_current_name(file_name)
        

        """Init the return value"""
	result = ""
        while True:
            if file_dialog.run() == gtk.RESPONSE_OK:
                result = file_dialog.get_filename()
                if (dialog_action==gtk.FILE_CHOOSER_ACTION_SAVE):
                    #Check if file already exists. If so, prompt user for
                    #replace
                    if os.path.isfile(result):                    
                        response = commonGUIElements.yes_no_dlg("Replace existing file "
                                                                +result+"?")
                        if response == gtk.RESPONSE_NO:
                            continue
            break

	file_dialog.destroy()
	return result

    def Action_One(self, widget):
        """
        TODO: Connect with parser class and classifier and output
        module
        """
        print "here"
        start,end = self.textBuffer.get_bounds()
        text = self.textBuffer.get_text(start, end)
        #text_xml_stripped = re.sub("<[^>]*>", "", text)
        
        return
        

if __name__ == "__main__":
    gui = GUI()
    gtk.main()
